package org.springframework.xml.xpath.proxy;

import org.springframework.xml.namespace.SimpleNamespaceContext;

import javax.xml.namespace.NamespaceContext;

/**
 * Builds a {@link NamespaceContext} using a spring-xml {@link SimpleNamespaceContext}
 *
 * @author Ray Krueger
 */
public class DefaultNamespaceContextBuilder implements NamespaceContextBuilder {

    public NamespaceContext buildNamespaceContext(final Class targetInterface) {

        SimpleNamespaceContext context = new SimpleNamespaceContext();

        NamespaceMapping[] namespaceMappings = getNamespaceMappings(targetInterface);
        if (namespaceMappings != null) {
            for (NamespaceMapping namespaceMapping : namespaceMappings) {
                context.bindNamespaceUri(namespaceMapping.prefix(), namespaceMapping.uri());
            }
        }

        return context;
    }

    @SuppressWarnings("unchecked")
    private NamespaceMapping[] getNamespaceMappings(Class targetInterface) {
        if (targetInterface.isAnnotationPresent(Namespaces.class)) {
            Namespaces namespaces = (Namespaces) targetInterface.getAnnotation(Namespaces.class);
            return namespaces.mappings();

        } else if (targetInterface.isAnnotationPresent(NamespaceMapping.class)) {
            return new NamespaceMapping[]{(NamespaceMapping) targetInterface.getAnnotation(NamespaceMapping.class)};

        }

        return null;
    }
}
